package com.haiheng.module_main.mode

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.http.get
import com.haiheng.library_base.http.patch
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.model.SingleLiveEvent
import com.haiheng.module_main.bean.res.bookcar.BookCarBookListRes
import com.haiheng.module_main.bean.res.bookcar.BookCarBookResult
import kotlinx.coroutines.launch

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/8/20 0020
 * @Version: 1.0
 */
class BookCarShelfViewModel : BaseViewModel() {
    // 使用MutableLiveData<List<Pair<String, String>>>来存储书车信息的键值对列表
    var _bookInfoList = SingleLiveEvent<List<BookCarBookResult>>()
    val bookInfoList: LiveData<List<BookCarBookResult>> = _bookInfoList
    var _faiMsg = SingleLiveEvent<String>()
    val faiMsg: LiveData<String> = _faiMsg
    fun getBookList() {
        viewModelScope.launch {
            try {
                val request = HttpRequest(API.BOOK_CAR_PATH.GET_BOOK_LIST_BY_MACHINEL)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .putQuery("MachineUuid",AppConstant.getCarUUid())
                    .putQuery("Page","1")
                    .putQuery("PageSize","99")

                var response = get<BookCarBookListRes>(request) {}
                if (response.errorCode.equals("0") && response.result != null && response.result.items != null){
                    _bookInfoList.postValue(response.result.items)
                }else{
                    _faiMsg.postValue("${response.message}")
                }

            } catch (ex: Exception) {
                _faiMsg.postValue("${ex.message}")
                LogWriter.d("查询图书数量异常：${ex.message}")
            }
        }
    }
    fun addBookShelf(bookInfoList: List<BookCarBookResult>) {
        viewModelScope.launch {
            try {
                val par = mutableMapOf<String, List<String>>()
                var barcodes = mutableListOf<String>()
                for (book in bookInfoList){
                    barcodes.add(book.barcode)
                }
                par.put("barcodes",barcodes)
                val request = HttpRequest(API.BOOK_CAR_PATH.ADD_BOOK_SHELF)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
//                    .putQueryParams(API.BOOK_CAR_PATH.PARAGE_BARCODES,barcodes)
                    .putPath(API.BOOK_CAR_PATH.PARAGE_MACHINEUUID,AppConstant.getCarUUid())
                    .setJsonObjec(par)

                var response = postJson<HttpResponse>(request) {}
                if (response.errorCode.equals("0")){
                    _faiMsg.postValue("上架成功")
                }else{
                    _faiMsg.postValue("${response.message}")
                    LogWriter.d("上架异常：${response}")
                }
            }catch (ex:Exception){
                _faiMsg.postValue("${ex}")
                LogWriter.d("上架异常：${ex.message}")
            }
        }
    }

    // 删除选中的书籍
    fun deleteSelectedBooks(selectedBookIds: List<String>) {
        // 假设 _bookInfoList.value 总是非空的
        val updatedList = _bookInfoList.value!!.filterNot { book ->
            selectedBookIds.contains(book.barcode)
        }
        _bookInfoList.value = updatedList
    }
    // 删除所有已选中的书籍
    fun deleteSelectedBooks() {
        val updatedList = _bookInfoList.value?.filterNot { it.isSelect } ?: emptyList()
        _bookInfoList.postValue(updatedList)
    }

    // 切换全选状态
    fun toggleSelectAll(isSelected: Boolean) {
        _bookInfoList.value?.let { books ->
            val updatedBooks = books.map { it.copy(isSelect = isSelected) }
            _bookInfoList.postValue(updatedBooks)
        }
    }

    fun clearBookData() {
        _bookInfoList.value?.let { addBookShelf(it) }
    }

    fun clearAllBookListData(){
        _bookInfoList.postValue(emptyList())
    }
}